package com.gzhryc.jdbc.log;

import com.gzhryc.jdbc.ConnectionFactory;
import com.gzhryc.jdbc.models.Parameters;
import org.apache.commons.lang3.StringUtils;

public class DefaultLogger extends Logger {

	private org.apache.log4j.Logger log;

	public DefaultLogger(org.apache.log4j.Logger log) {
		this.log = log;
	}

	public void sql(String jdbcKey,String message,Parameters parameters) {
		if (ConnectionFactory.getConnectInfo(jdbcKey).getLogLevel() == 2) {
			String sql = "[sql]" + message + ";";
			if (parameters != null) {
				String p = parameters.toString();
				if(StringUtils.isNotBlank(p)) {
					sql = sql + " p = " + p;
				}
			}
			if (log != null) {
				log.info(sql);
			} else {
				System.out.println(sql);
			}
		}
	}

	@Override
	public void sql(String jdbcKey, String message) {
		sql(jdbcKey,message,null);
	}

	public void info(String message, Object... objs) {
		if (log != null) {
			log.info(LogAnalysisUtils.out(message, objs));
		} else {
			System.out.println("[info]" + LogAnalysisUtils.out(message, objs));
		}
	}

	public void error(String message, Object... objs) {
		if (log != null) {
			Throwable throwable = null;
			if (objs != null && objs.length > 0) {
				for (Object obj : objs) {
					if (Throwable.class.isInstance(obj)) {
						throwable = Throwable.class.cast(obj);
						break;
					}
				}
			}
			if (throwable != null) {
				log.error(LogAnalysisUtils.out(message, objs), throwable);
			} else {
				log.error(LogAnalysisUtils.out(message, objs));
			}
		} else {
			System.out.println("[error]" + LogAnalysisUtils.out(message, objs));
		}
	}

	public void debug(String message, Object... objs) {
		if (log != null) {
			Throwable throwable = null;
			if (objs != null && objs.length > 0) {
				for (Object obj : objs) {
					if (Throwable.class.isInstance(obj)) {
						throwable = Throwable.class.cast(obj);
						break;
					}
				}
			}
			if (throwable != null) {
				log.warn(LogAnalysisUtils.out(message, objs), throwable);
			} else {
				log.warn(LogAnalysisUtils.out(message, objs));
			}
		} else {
			System.out.println("[debug]" + LogAnalysisUtils.out(message, objs));
		}
	}
}
